package com.lin.threadlocal;

import java.util.Random;
import java.util.concurrent.TimeUnit;

public class ThreadLocalTest {
    private static final ThreadLocal<Integer> threadLocal = new ThreadLocal<>();

    public static void main(String[] args) {
        Random random = new Random();
        Thread thread1 = new Thread(() -> {
            int nextInt = random.nextInt(100);
            System.out.println(Thread.currentThread() + " set :" + nextInt);
            threadLocal.set(nextInt);
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread() + " get ：" + threadLocal.get());
        });

        Thread thread2 = new Thread(() -> {
            System.out.println(Thread.currentThread() + " get :" + threadLocal.get());
            int nextInt = random.nextInt(100);
            System.out.println(Thread.currentThread() + " set :" + nextInt);
            threadLocal.set(nextInt);
            System.out.println(Thread.currentThread() + " get ：" + threadLocal.get());
        });

        thread1.start();
        thread2.start();
    }
}
